﻿using LuDragon.Common.Constant;
using LuDragon.Common.Utils;
using LuDragon.Web.Areas.WxApi.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace LuDragon.Web.Areas.WxApi.Controllers
{
    /// <summary>
    /// 微信登录控制器
    /// </summary>
    public class WxLoginController : ApiController
    {
        /// <summary>
        /// 微信登录
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public HttpResult Login(string code)
        {
            var url = "https://api.weixin.qq.com/sns/jscode2session";
            var appId = "appid=" + ConfigurationManager.AppSettings["AppId"];
            var secret = "secret=" + ConfigurationManager.AppSettings["AppSecret"];
            var js_code = "js_code=" + code;
            var grant_type = "grant_type=authorization_code";
            var res = HttpHelper.HttpGet(url, appId + "&" + secret + "&" + js_code + "&" + grant_type);
            var data = res.ToObject<WxLoginResult>();
            if (data.openid != null)
            {
                return new HttpResult
                {
                    Code = 200,
                    Msg = "登录成功",
                    Data = data
                };
            }
            else
            {
                return new HttpResult
                {
                    Code = 40029,
                    Msg = "invalid code"               
                };
            }

        }
    }
}
